const app = getApp();

Page({
  data: {
    phone: '',
    code: '',
    password: '',
    userType: 'student', // 默认为学生
    countdown: 0,
    loading: false,
    errorMsg: '',
    loginType: 'phone', // phone或wechat
    authType: 'password' // code或password，默认使用密码登录
  },

  onLoad() {
    // 检查是否已登录
    if (app.globalData.token) {
      wx.switchTab({
        url: '/pages/schedules/schedules'
      });
    }
  },

  // 切换用户类型
  switchUserType(e) {
    this.setData({
      userType: e.currentTarget.dataset.type,
      errorMsg: ''
    });
  },

  // 切换登录方式
  switchLoginType(e) {
    this.setData({
      loginType: e.currentTarget.dataset.type,
      errorMsg: ''
    });
  },

  // 切换认证方式（验证码或密码）
  switchAuthType(e) {
    this.setData({
      authType: e.currentTarget.dataset.type,
      errorMsg: ''
    });
  },

  // 输入手机号
  inputPhone(e) {
    this.setData({
      phone: e.detail.value,
      errorMsg: ''
    });
  },

  // 输入验证码
  inputCode(e) {
    this.setData({
      code: e.detail.value,
      errorMsg: ''
    });
  },

  // 输入密码
  inputPassword(e) {
    this.setData({
      password: e.detail.value,
      errorMsg: ''
    });
  },

  // 获取验证码
  getVerificationCode() {
    const { phone, countdown } = this.data;
    
    // 倒计时中不能再次发送
    if (countdown > 0) return;
    
    // 手机号验证
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      this.setData({ errorMsg: '请输入正确的手机号' });
      return;
    }
    
    wx.showLoading({ title: '发送中...' });
    
    // 调用发送验证码接口
    app.sendVerificationCode(phone)
      .then(() => {
        wx.hideLoading();
        wx.showToast({ title: '验证码已发送', icon: 'success' });
        
        // 设置倒计时
        this.setData({ countdown: 60 });
        this.startCountdown();
      })
      .catch(err => {
        wx.hideLoading();
        this.setData({ errorMsg: err.message || '验证码发送失败' });
      });
  },
  
  // 倒计时
  startCountdown() {
    const timer = setInterval(() => {
      if (this.data.countdown <= 1) {
        clearInterval(timer);
        this.setData({ countdown: 0 });
      } else {
        this.setData({ countdown: this.data.countdown - 1 });
      }
    }, 1000);
  },

  // 手机号登录
  phoneLogin() {
    const { phone, code, password, userType, authType } = this.data;

    // 表单验证
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      this.setData({ errorMsg: '请输入正确的手机号' });
      return;
    }

    if (authType === 'code' && !code) {
      this.setData({ errorMsg: '请输入验证码' });
      return;
    }

    if (authType === 'password' && !password) {
      this.setData({ errorMsg: '请输入密码' });
      return;
    }

    this.setData({ loading: true });

    // 调用登录方法，默认使用password方式
    const loginType = authType || 'password';
    app.phoneLogin(phone, loginType === 'code' ? code : password, userType, loginType)
      .then(() => {
        wx.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 1500
        });
        // 登录成功，跳转到首页
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/schedules/schedules'
          });
        }, 1500);
      })
      .catch(err => {
        this.setData({
          errorMsg: err.message || '登录失败',
          loading: false
        });
      });
  },

  // 微信一键登录
  wechatLogin() {
    const { userType } = this.data;
    this.setData({ loading: true });

    app.wechatLogin(userType)
      .then(() => {
        wx.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 1500
        });
        // 登录成功，跳转到首页
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/schedules/schedules'
          });
        }, 1500);
      })
      .catch(err => {
        this.setData({
          errorMsg: err.message || '微信登录失败',
          loading: false
        });
      });
  },

  // 登录按钮点击
  login() {
    if (this.data.loginType === 'phone') {
      this.phoneLogin();
    } else {
      this.wechatLogin();
    }
  },

  // 去注册页面
  goToRegister() {
    wx.navigateTo({
      url: '/pages/register/register'
    });
  }
}); 